// Copyright 2024 Moralfly Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package orm

import (
	"fmt"
	"reflect"
	"strings"
)

// mysql dbBaser implementation.
type dbBaseKingBase struct {
	dbBase
}

var _ dbBaser = new(dbBaseKingBase)

// create new mysql dbBaser.
func newdbBaseKingBase() dbBaser {
	b := new(dbBaseKingBase)
	b.ins = b
	return b
}

// get mysql operator.
func (d *dbBaseKingBase) OperatorSQL(operator string) string {
	return mysqlOperators[operator]
}

// get mysql table field types.
func (d *dbBaseKingBase) DbTypes() map[string]string {
	return mysqlTypes
}

// show table sql for mysql.
func (d *dbBaseKingBase) ShowTablesQuery() string {
	return "SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = DATABASE()"
}

// show columns sql of table for mysql.
func (d *dbBaseKingBase) ShowColumnsQuery(table string) string {
	return fmt.Sprintf("SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE FROM information_schema.columns "+
		"WHERE table_schema = DATABASE() AND table_name = '%s'", table)
}

// execute sql to check index exist.
func (d *dbBaseKingBase) IndexExists(db dbQuerier, table string, name string) bool {
	row := db.QueryRow("SELECT count(*) FROM information_schema.statistics "+
		"WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?", table, name)
	var cnt int
	row.Scan(&cnt)
	return cnt > 0
}

func (d *dbBaseKingBase) ReplaceMarks(query *string, values *[]interface{}) {
	q := *query
	if num := strings.Count(q, "?"); num > 0 && values != nil {
		var v = *values
		var newQuery string
		var newValues []interface{}
		for i := 0; i < len(v); i++ {
			if reflect.TypeOf(v[i]).Kind() == reflect.Slice {
				// 使用反射获取数组的类型信息
				arrayValue := reflect.ValueOf(v[i])
				for i := 0; i < arrayValue.Len(); i++ {
					newValues = append(newValues, arrayValue.Index(i).Interface())
				}
			} else {
				newValues = append(newValues, v[i])
			}
		}
		if newValues != nil && num == len(newValues) {
			strList := strings.Split(q, "?")
			for i := 0; i < len(strList); i++ {
				newQuery += strList[i]
				if i < len(strList)-1 {
					newQuery += fmt.Sprintf("'%v'", newValues[i])
				}
			}
			*query = newQuery
			*values = []interface{}{}
		}
	}
}

func (d *dbBaseKingBase) InsertValue(q dbQuerier, mi *modelInfo, isMulti bool, names []string, values []interface{}) (int64, error) {
	Q := d.ins.TableQuote()
	marks := make([]string, len(names))
	for i := range marks {
		marks[i] = "?"
	}

	sep := fmt.Sprintf("%s, %s", Q, Q)
	qmarks := strings.Join(marks, ", ")
	columns := strings.Join(names, sep)
	multi := len(values) / len(names)

	if isMulti {
		qmarks = strings.Repeat(qmarks+"), (", multi-1) + qmarks
	}

	query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks)

	d.ins.ReplaceMarks(&query, &values)

	if isMulti || !d.HasReturningID(mi, &query) {
		res, err := q.Exec(query, values...)
		if err == nil {
			if isMulti {
				return res.RowsAffected()
			}
		}
		return 0, err
	}
	row := q.QueryRow(query, values...)
	var id int64
	err := row.Scan(&id)
	return id, err
}
